BTRepeater = BTDecorator:New()

local this = BTRepeater
this.name = "Repeater Task"

function this:New(count, endOnFailure)
	local o = {}
	setmetatable(o, self)
	self.__index = self
	o.childTasks = {}
	o.count = count or -1                       --执行次数，-1为循环执行
	o.endOnFailure = endOnFailure or false      --子节点返回Failure时，是否结束
	o.executionCount = 0                        --当前执行次数
	return o
end

function this:OnUpdate()
	if (not self.currentChildTask) then
		self.currentChildTask = self:GetChild()
		if (not self.currentChildTask) then
			self.executionStatus = BTTaskStatus.Failure
			return BTTaskStatus.Failure
		end
	end
	local canExecute = false
	if (((self.count == -1) or (self.executionCount < self.count)) and
		((not self.endOnFailure) or (self.endOnFailure and self.executionStatus ~= BTTaskStatus.Failure))) then
		canExecute = true
	end
	if (canExecute) then
		self.executionStatus = self.currentChildTask:OnUpdate()
		self.executionCount = self.executionCount + 1
	end
	if (self.endOnFailure and self.executionStatus == BTTaskStatus.Failure) then
		self:Reset()
		self.executionStatus = BTTaskStatus.Success
		return BTTaskStatus.Success
	elseif (self.executionCount == self.count) then
		self:Reset()
		self.executionStatus = BTTaskStatus.Success
		return BTTaskStatus.Success
	else
		self.executionStatus = BTTaskStatus.Running
		return BTTaskStatus.Running
	end
end

function this:Reset()
	self.executionStatus = BTTaskStatus.Inactive
	self.executionCount = 0
	BTParentTask.Reset(self)
end